﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <vector>
#include <string>

#include <QDebug>

#include "lua.hpp"
#include "LuaHelper.h"
#include "ExprtkHelper.h"


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    init();
}

MainWindow::~MainWindow()
{
    LuaHelper::freeInstance();
    delete ui;
}

void MainWindow::init()
{
    /*----------------------c++ exprtk---------------------*/
    testExprtk();

    /*----------------------lua------------------------*/
    // testFunc2();
}

void MainWindow::testExprtk()
{
    //
    std::string expre = "x^2 + x - sqrt(x)";
    QVariant result;
    ExprtkHelper::instance().execute<double>(expre, 10.0, result);
    qDebug() << "result: " << result;
}

void MainWindow::testFunc2()
{
    QString filePath = QCoreApplication::applicationDirPath() + "/lua_func.lua";
    if(!LuaHelper::getInstance()->loadLuaModel(filePath)){
        qDebug() << "load LuaModel error";
    }

    // 调用规则，需要给未知数x，带一堆括号(x)
    const char* mathFormula = "cos(x)";
    QVariant result;
    auto bResult = LuaHelper::getInstance()->execLuaWithMathFormula(0, mathFormula,result);

    if(bResult)
        qDebug() << "math result: " << result.toDouble();
    else{
        qDebug() << "formula error: " << result.toString();
    }
}

void MainWindow::testFunc(){
    lua_State* L = luaL_newstate();
    luaL_openlibs(L);

    // 加载Lua脚本
    if (luaL_dofile(L, "lua_func.lua")) {
        const char* error = lua_tostring(L, -1); // 获取错误信息
        qDebug() << "Error loading Lua script: " << error;
        lua_pop(L, 1); // 弹出错误信息
        lua_close(L); // 关闭Lua虚拟机
        return ;
    }

    lua_getglobal(L, "LuaFunctionTypeManage");


    lua_pushinteger(L, 6);
    lua_pushinteger(L, 1);
    lua_pushinteger(L, 0);

    if (lua_pcall(L, 3, 1, 0) != LUA_OK)
    {
        qDebug() << "Error calling Lua function: " << lua_tostring(L, -1);
        lua_close(L);
        return ;
    }

    // 获取返回值
    if (lua_isnumber(L, -1))
    {
        double result = lua_tonumber(L, -1);
        qDebug() << "Arithmetic_operation value: " << result;
    }

    if (lua_isstring(L, -1))
    {
        const char* result = lua_tostring(L, -1);
        qDebug() << "Quantized value: " << result;
    }


    // 关闭Lua
    lua_close(L);
}

